//
//  MyViewController.m
//  GuoBuGaForIphone
//
//  Created by zhangwo on 16/10/26.
//  Copyright © 2016年 GuoBuGa. All rights reserved.
//

#import "MyViewController.h"
#import "InformationViewController.h"
#import "ModifyHeadViewController.h"
//#import "NewTaskViewController.h"
#import "MyTaskViewController.h"


@interface MyViewController ()

@end

@implementation MyViewController

@synthesize tableView = _tableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor bgColor]];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userStatusChanged) name:UserStatusChangedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setHeadView) name:UserImageChangedNotification object:nil];
    
    self.automaticallyAdjustsScrollViewInsets = NO;//不允许自动设置tableView的高度
    self.navigationController.delegate = self;
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.height = SHEIGHT - self.tabBarController.tabBar.height;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    
    [_tableView registerClass:[TitleViewCell class] forCellReuseIdentifier:@"listCell"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"taskCell"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"loginCell"];
    [self.view addSubview:_tableView];
    [self setHeadView];
    
    _taskView = [[TaskView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, 90)];
    _taskView.touchDelegate = self;
    
    _loginout = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, SWIDTH-40, 50)];
    _loginout.textAlignment = NSTextAlignmentCenter;
    _loginout.layer.cornerRadius = 20;
    _loginout.font = [UIFont systemFontOfSize:16.0];
    
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)setHeadView{
    _headerView = [[MyHeadView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, 120)];
    _tableView.tableHeaderView = _headerView;
    if ([[BJUserStatus sharedStatus] isLogined]) {
        [_headerView.imageView sd_setImageWithURL:[NSURL URLWithString:[[BJUserStatus sharedStatus] userpic]]];
        [_headerView.textLabel setText:[[BJUserStatus sharedStatus] username]];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseImage:)];
        [_headerView.imageView addGestureRecognizer:tap];
        [_headerView.imageView setUserInteractionEnabled:YES];
        
        //设置
        _buttonSetting = [[UIButton alloc] initWithFrame:CGRectMake(SWIDTH-40, 69, 22, 22)];
        [_buttonSetting setBackgroundImage:[UIImage imageNamed:@"icon-setting-image.png"] forState:UIControlStateNormal];
        [_buttonSetting addTarget:self action:@selector(showSetting) forControlEvents:UIControlEventTouchUpInside];
        [_tableView addSubview:_buttonSetting];
        
    }else{
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showLogin)];
        UIImageView *avatar = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-head-photo.png"]];
        [_headerView setImageView:avatar];
        [_headerView addGestureRecognizer:tap];
        [_headerView setUserInteractionEnabled:YES];
    }
}

- (void)taskView:(TaskView *)taskView didSelectedAtItem:(NSDictionary *)data
{
    NSInteger tag = [[data objectForKey:@"tag"] intValue];
    if ([[BJUserStatus sharedStatus] isLogined]) {
        MyTaskViewController *myTaskView = [[MyTaskViewController alloc] init];
        switch (tag) {
            case 1:
                myTaskView.newsTaskView = @"1";
                myTaskView.title = @"新任务";
                break;
            case 2:
                myTaskView.myResponsibilityView = @"2";
                myTaskView.title = @"我负责的";
                break;
            case 3:
                myTaskView.myParticipateView = @"3";
                myTaskView.title = @"我参与的";
                break;
            default:
                myTaskView.newsReleaseView = @"4";
                myTaskView.title = @"我发布的";
                break;
        }
        [self.navigationController pushViewController:myTaskView animated:YES];
    }else
    {
        [self showLogin];
    }
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 4;
    }
    if (section == 1) {
        return 1;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 90;
        }
        if (indexPath.row == 1) {
            return 50;
        }
        if (indexPath.row == 2) {
            return 50;
        }
        if (indexPath.row == 3) {
            return 50;
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 50;
        }
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"taskCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell addSubview:_taskView];
            return cell;
        }
        if (indexPath.row == 1) {
            TitleViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleDefault;
            cell.title = @"我的部门成员";
            return cell;
        }
        if (indexPath.row == 2) {
            TitleViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleDefault;
            cell.title = @"用户指南";
            return cell;
        }
        if (indexPath.row == 3) {
            TitleViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"listCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleDefault;
            float cacheSize = (float)[[SDImageCache sharedImageCache] getSize]/1048576;
            cell.title = @"清除缓存";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2fMB",cacheSize];
            cell.accessoryType = UITableViewCellAccessoryNone;
            return cell;
        }
    }
    if (indexPath.section == 1) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"loginCell" forIndexPath:indexPath];
        [cell addSubview:_loginout];
        if (indexPath.row == 0) {
            if ([[BJUserStatus sharedStatus] isLogined]) {
                _loginout.text = @"退出登录";
                _loginout.textColor = [UIColor redColor];
            }else {
                _loginout.text = @"登录";
                _loginout.textColor = [UIColor blackColor];
            }
        }
        return cell;
    }
    return [[UITableViewCell alloc] init];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell setSelected:NO animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 1) {
            MemberViewController *menberView = [[MemberViewController alloc] init];
            [self.navigationController pushViewController:menberView animated:YES];
        }
        if (indexPath.row == 2) {
            AboutusViewController *aboutusView = [[AboutusViewController alloc] init];
            [self.navigationController pushViewController:aboutusView animated:YES];
        }
        if (indexPath.row == 3) {
            [[SDImageCache sharedImageCache] clearDisk];
            [[DSXUI standardUI] showPopViewWithStyle:DSXPopViewStyleDefault Message:@"已成功清除缓存"];
            [_tableView reloadData];
        }
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            if ([[BJUserStatus sharedStatus] isLogined]) {
                [[BJUserStatus sharedStatus] logout];
            }
            [self showLogin];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc] init];
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:12.0];
    if (section == 0) {
        label.text = @"     任务";
    }
    return label;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

#pragma mark -
- (void)userStatusChanged{
    [[BJUserStatus sharedStatus] reloadData];
    [self setHeadView];
    [_tableView reloadData];
}

- (void)showLogin{
    [[BJUserStatus sharedStatus] showLoginFromViewController:self];
}

- (void)showSetting{
    if ([[BJUserStatus sharedStatus] isLogined]) {
        ModifyHeadViewController *setttingView = [[ModifyHeadViewController alloc] init];
        DSXNavigationController *nav = [[DSXNavigationController alloc] initWithRootViewController:setttingView];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    }else {
        [self showLogin];
    }
}

- (IBAction)chooseImage:(id)sender
{
    UIActionSheet *sheet = [[UIActionSheet alloc]init];
    [sheet addButtonWithTitle:@"拍照"];
    [sheet addButtonWithTitle:@"从相册选择"];
    [sheet addButtonWithTitle:@"取消"];
    [sheet setCancelButtonIndex:2];
    [sheet setDelegate:self];
    sheet.tag = 255;
    [sheet showInView:self.view];
}

-(void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 255) {
        UIImagePickerController *pickController = [[UIImagePickerController alloc] init];
        pickController.delegate = self;
        if (buttonIndex == 0) {
            pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:pickController animated:YES completion:nil];
        }
        if (buttonIndex == 1) {
            pickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:pickController animated:YES completion:nil];
        }
    }
}

#pragma mark - image picker delegte
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];//原图片
    // 保存图片至本地
    [self saveImage:image withName:@"currentImage.png"];
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];
    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    [_headerView.imageView setImage:savedImage];
    _headerView.imageView.tag = 100;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
}


#pragma mark - navigationController delegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    if (viewController == self) {
        self.navigationController.navigationBarHidden = YES;
    }else {
        self.navigationController.navigationBarHidden = NO;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
